package win.ganbo.softwareFive.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import win.ganbo.softwareFive.domain.LoginToken;
import win.ganbo.softwareFive.utils.ConstantConfig;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String uri = request.getRequestURI();
        if (uri.contains("static"))
            return true;

        //截掉uri中项目部署的项目名,获取访问的资源uri
        String contextPath = request.getContextPath();
        if (StringUtils.isNotBlank(contextPath)) {
            if (uri.indexOf(contextPath) >= 0)
                uri = uri.substring(contextPath.length() + 1);
        }
        if (uri.startsWith("/"))
            uri = uri.substring(1);

        if (StringUtils.isNotBlank(uri) && uri.contains("user")) {
            LoginToken loginToken = (LoginToken) request.getSession()
                .getAttribute(ConstantConfig.USER_IN_SESSION);

            if (loginToken == null) {
                //                response.sendRedirect(contextPath + "/noSession.jsp");
                response.sendRedirect(contextPath + "/sys/loginUI");
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
    }
    
    
    /**
     * 获取访问方法
     * @param request
     * @return
     */
    private String getBaseURL(HttpServletRequest request) {
        String url = request.getScheme() 
                    + "://" 
                    + request.getServerName() 
                    + ":"
                    + request.getServerPort() 
                    + request.getContextPath() 
                    + request.getRequestURI();
        return url;
    }

}
